package aos.voting.entity;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Vector;

public class DataSet implements Comparable<DataSet>, Serializable {
	private static final long serialVersionUID = 1L;
	protected int dataNum;
	protected Vector<Data> dataset;
	private HashMap<Integer, Integer> clientId2TS;

	public DataSet(int dataNum) {
		this.dataNum = dataNum;
		dataset = new Vector<Data>();
		for (int i = 0; i < dataNum; ++i) {
			dataset.add(new Data(i, 0, 0));
		}
		this.clientId2TS = new HashMap<Integer, Integer>();
	}

	public String toString() {
		String ts = "";
		for (Integer clientId : clientId2TS.keySet()) {
			ts += "(" + clientId + ":" + clientId2TS.get(clientId) + ")";
		}
		String s = "";
		for (int i = 0; i < dataNum; ++i) {
			s += dataset.get(i).toString();
		}
		return ts + " " + s;
	}

	public Data get(int dataId) {
		return dataset.get(dataId);
	}

	public int getTS(int clientId) {
		if (!clientId2TS.containsKey(clientId)) {
			return 0;
		}
		return clientId2TS.get(clientId);
	}

	public void increase(int dataId, int value, int clientId, int ts) {
		if (!clientId2TS.containsKey(clientId)
				|| clientId2TS.get(clientId) < ts) {
			dataset.get(dataId).increase(value);
			clientId2TS.put(clientId, ts);
		}
	}

	@Override
	public int compareTo(DataSet dataset) {
		if (dataset.clientId2TS.size() != clientId2TS.size()) {
			return dataset.clientId2TS.size() > clientId2TS.size() ? -1 : 1;
		} else {
			for (Integer clientId : clientId2TS.keySet()) {
				if (dataset.clientId2TS.get(clientId) > clientId2TS
						.get(clientId))
					return -1;
			}
		}
		return 1;
	}

}
